<html>
<body>

<script src="../../resources/js-test.js"></script>

<script>

description("This test checks that Page Visibility state events are propagated to child frames.");

var jsTestIsAsync = true;

function makePageVisible() {
    if (window.testRunner)
        testRunner.setMainWindowHidden(false);
}

function makePageHidden() {
    if (window.testRunner)
        testRunner.setMainWindowHidden(true);
}

function checkIsPageVisible() {
    debug("Main Page:");
    shouldBeEqualToString("document.visibilityState", "visible");
    shouldBeFalse("document.hidden");
}

function checkIsPageHidden() {
    debug("Main Page:");
    shouldBeEqualToString("document.visibilityState", "hidden");
    shouldBeTrue("document.hidden");
}

function checkIsChildFrameVisible() {
    debug("Child Frame:");
    shouldBeEqualToString("childFrame.contentDocument.visibilityState",
                          "visible");
    shouldBeFalse("childFrame.contentDocument.hidden");
}

function checkIsChildFrameHidden() {
    debug("Child Frame:");
    shouldBeEqualToString("childFrame.contentDocument.visibilityState",
                          "hidden");
    shouldBeTrue("childFrame.contentDocument.hidden");
}

// We will try to change the visibility states as:
//  0 - visible. (Initial - i.e. on load).
//  1 - hidden
//  2 - visible
var numVisibilityChanges = 0;

var childFrame;

function startTest() {
    childFrame = document.getElementById("childFrame");
    childFrame.contentDocument.addEventListener(
        "visibilitychange", onChildFrameVisibilityChange, false);
    document.addEventListener("visibilitychange",
                              onVisibilityChange, false);

    checkIsPageVisible();
    checkIsChildFrameVisible();

    numVisibilityChanges++;
    makePageHidden();
}

var numFinishes = 0;
function finishTest() {
    numFinishes++;
    if (numFinishes < 2) {
      return;
    }
    finishJSTest();
}

function onVisibilityChange() {
    if (numVisibilityChanges == 1) {
        checkIsPageHidden();
        return;
    } else if (numVisibilityChanges == 2) {
        checkIsPageVisible();
        finishTest();
        return;
    } else {
        testFailed("Too many visibility transitions");
        finishTest();
        return;
    }
}

function onChildFrameVisibilityChange() {
    if (numVisibilityChanges == 1) {
        checkIsChildFrameHidden();
        numVisibilityChanges++;
        makePageVisible();
        return;
    } else if (numVisibilityChanges == 2) {
        checkIsChildFrameVisible();
        finishTest();
        return;
    } else {
        testFailed("Child Frame: Too many visibility transitions");
        finishTest();
    }
}

</script>


<iframe id="childFrame" onload="startTest()"></iframe>
</body>
</html>
